<template>
  <div class="share-card" :class="type == 2 ? 'scrollBox' : ''">
    <div class="badge-header">
      <bottom-open-app-adv v-if="!$UA.isJM"></bottom-open-app-adv>
      <van-nav-bar
        title="分享徽章海报"
        left-arrow
        @click-left="back"
        class="my-nav-bar"
        v-if="$UA.isJM"
      ></van-nav-bar>
    </div>
    <div class="share-page">
      <!-- 页面最终生成的图片 -->
      <img :src="imgUrl" alt="" v-if="imgUrl" />
      <div v-else class="load-box">
        <van-loading vertical>正在加载...</van-loading>
      </div>
      <div class="hidden">
        <!-- 调试时打开 -->
        <!-- <div> -->
        <!-- type为1代表分享徽章海报 -->
        <div class="content" :class="type == 1 ? 'back' : ''" ref="imageWrapper">
          <div class="info-header" :class="{ onlyone: type == 2 }">
            <div class="info">
              <div class="avatar">
                <img :src="avatar64" v-if="avatar64" />
              </div>
              <span class="name">{{ $userInfo.nickname }}</span>
            </div>
            <div class="badge-num" v-if="type == 1">
              共
              <span class="num">{{ count }}</span>
              枚积幕徽章
            </div>
          </div>
          <!-- 徽章墙 -->
          <div class="info-badge" v-if="type == 1">
            <div class="badge-item" v-for="(item, index) in badgeData" :key="index">
              <div v-if="item.owned == 1">
                <div class="wall-img">
                  <img
                    v-if="listIcon64[index]"
                    :src="listIcon64[index]"
                    crossorigin="anonymous"
                    @load="loadImg"
                    @error="errorImg"
                  />
                </div>
                <div class="wall-title">{{ item.title }}</div>
              </div>
            </div>
          </div>
          <!-- 单个徽章 -->
          <div class="info-badge-single" v-if="type == 2">
            <div class="outer-box">
              <div class="test">
                <img class="bg" src="../../assets/images/badge/share-badge-bg.png" />
                <img
                  v-if="singleIcon64"
                  class="badge-img"
                  :src="singleIcon64"
                  crossorigin="anonymous"
                  @load="loadImg"
                  @error="errorImg"
                />
              </div>
              <!-- <div class="badge-filter">
                <div class="badge-start">
                  <img src="../../assets/images/badge/share-starts.png" />
                </div>
              </div> -->
              <div class="bottom-title">
                <div class="badge-title">{{ badgeSingle.title }}</div>
                <div class="work-num">{{ badgeSingle.ownedCondition }}</div>
              </div>
            </div>

            <div class="jimu-app">
              <img src="../../assets/images/badge/jimu_app.png" />
            </div>
          </div>
          <!-- 二维码 -->
          <div class="info-footer">
            <div class="info-box">
              <canvas id="my-qr-code"></canvas>
              <div class="info-title">
                <span class="invite">
                  邀请你扫码加入积幕
                  <br />
                </span>
                <span class="title">积幕，堆积无穷灵感</span>
              </div>
            </div>
            <div class="icon-jimu">
              <img src="../../assets/images/badge/logo.png" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div :class="type == 1 ? 'box-height' : ''" v-if="shareInfo.image">
      <share-bottom-btn :shareInfo.sync="shareInfo"></share-bottom-btn>
    </div>
  </div>
</template>
<script>
  import QRCode from 'qrcode';
  import html2canvas from 'html2canvas';
  import mixins from 'mixins';
  import { NavBar, Loading, Toast } from 'vant';
  import ShareBottomBtn from '../../components/ShareBottomBtn.vue';
  import qs from 'qs';
  import BottomOpenAppAdv from '../../components/BottomOpenAppAdv.vue';

  export default {
    mixins: [mixins],
    data() {
      return {
        shareInfo: {},
        imgUrl: '',
        avatar: '',
        imgIsLoad: false, //加载头像等远端图片
        screenHeight: document.body.clientHight, //获取屏幕的高度
        badgeData: [], //徽章墙数据
        badgeSingle: {}, //单个徽章数据
        count: 0, //我获取的徽章数
        dataLoading: false,
        loading: false, //海报图片加载状态
        avatar64: '',
        singleIcon64: '',
        listIcon64: [],
        badgeListImage: [], //徽章墙的图片
        type: '', //海报类型
        shareUrl: '', //二维码分享地址
        // 二维码配置
        opts: {
          errorCorrectionLevel: 'L', //容错级别
          type: 'image/png', //生成的二维码类型
          quality: 0.3, //二维码质量
          margin: 0, //二维码留白边距
          width: 60, //宽
          height: 60, //高
          color: {
            dark: '#000', //前景色
            light: '#fff', //背景色
          },
        },
      };
    },
    components: {
      'van-nav-bar': NavBar,
      'van-loading': Loading,
      ShareBottomBtn,
      BottomOpenAppAdv,
    },
    watch: {
      $userInfo: {
        handler(val) {
          this.avatar = val.avatar;
        },
      },
      dataLoading(val) {
        if (!val) {
          this.imgToBase64();
        }
      },
      imgIsLoad(newVal, oldVal) {
        if (newVal && !oldVal) {
          this.$nextTick(() => {});
        }
      },
    },
    created() {
      // 获取传递的信息
    },
    mounted() {
      // 设置标题
      this.$appService.setNav({
        title: '分享徽章海报',
        fullscreen: true,
        statusBarStyle: 1,
      });
      // 这里是禁止微信分享
      this.hideWXShare();
      // this.init();
      this.type = qs.parse(window.location.search.substr(1)).type;
      this.uuid = qs.parse(window.location.search.substr(1)).uuid;
      this.badgeId = qs.parse(window.location.search.substr(1)).badgeId;
      if (this.type == 1) {
        this.shareUrl =
          `https://${
            process.env.NODE_ENV === 'development' ? 'dev-' : ''
          }jimu-h5.movtile.com/activity/badgewall.html?uuid=` + this.uuid;
        this.getBadgeWall();
      } else {
        this.shareUrl =
          `https://${
            process.env.NODE_ENV === 'development' ? 'dev-' : ''
          }jimu-h5.movtile.com/activity/badgedetail.html?badgeId=` +
          this.badgeId +
          '&uuid=' +
          this.uuid;
        this.getBadgeDetail();
      }
    },
    methods: {
      async imgToBase64() {
        let pArr = [];
        if (!this.avatar) {
          await this.getUserInfo();
        }
        this.$nextTick(() => {
          pArr.push(
            this.getBase64Image(this.avatar, 'avatar').then((res) => {
              this.avatar64 = res;
            }),
          );
          if (this.type == 1) {
            this.badgeListImage.map((i, index) => {
              pArr.push(
                this.getBase64Image(i, 'badgeList').then((res) => {
                  this.listIcon64.push(res);
                }),
              );
            });
          }
          if (this.type == 2) {
            pArr.push(
              this.getBase64Image(this.badgeSingle.activeIcon, 'badgeSingle').then((res) => {
                this.singleIcon64 = res;
              }),
            );
          }
          Promise.all(pArr).then(() => {
            setTimeout(() => {
              //转完开始画图
              this.init();
            }, 500);
          });
        });
      },
      //获取徽章墙
      getBadgeWall() {
        this.dataLoading = true;
        this.$service
          .UserBadgeWall({})
          .then((res) => {
            this.count = res.count;
            res.badges.forEach((i) => {
              if (i.owned == 1) {
                this.badgeData.push(i);
                this.badgeListImage.push(i.activeIcon);
              }
            });
            this.dataLoading = false;
          })
          .catch((err) => {
            Toast(err.message);
          });
      },
      //获取单个徽章
      getBadgeDetail() {
        this.dataLoading = true;
        this.$service
          .UserBadgeDetail({
            id: this.badgeId,
            uid: this.uuid,
          })
          .then((res) => {
            this.badgeIndex = res.findIndex((_) => _.id == this.badgeId);
            this.badgeSingle = res[this.badgeIndex];
            this.dataLoading = false;
          })
          .catch((err) => {
            Toast(err.message);
          });
      },
      back() {
        this.$appService.exit(); //返回上一层
      },
      //加载头像
      loadImg() {
        this.imgIsLoad = true;
      },
      //图片加载失败
      errorImg(e) {
        if (e.target.tagName == 'IMG') {
          // Toast('加载失败再加载')
          if (this.type == 1) {
            this.badgeData.map((item) => {
              e.src = item.activeIcon;
            });
          } else if (this.type == 2) {
            e.src = this.badgeSingle.activeIcon;
          }
          this.$forceUpdate();
        }
      },
      init() {
        this.loading = true;
        // 生成二维码
        let msg = document.getElementById('my-qr-code');
        // 将获取到的数据（val）画到msg（canvas）上
        QRCode.toCanvas(msg, this.shareUrl, this.opts, function (error) {
          console.log(error);
        });
        // 生成图片

        html2canvas(this.$refs.imageWrapper, {
          allowTaint: true,
          useCORS: true,
          scrollY: 0,
          scale: 6,
          // dpi: 300, // 处理模糊
        }).then((canvas) => {
          this.loading = false;
          let dataURL = canvas.toDataURL('image/png');
          this.imgUrl = dataURL;
          this.$appService.setNav({
            title: '分享徽章海报',
            image: this.imgUrl,
          });
          this.shareInfo.image = this.imgUrl;
        });
      },
      getBase64Image(imgurl, key) {
        return new Promise((resolve, reject) => {
          var img = new Image();
          img.setAttribute('crossOrigin', 'anonymous');
          var canvas = document.createElement('canvas');
          let _imgurl = imgurl;
          switch (key) {
            case 'badgeSingle':
            case 'badgeList':
              img.src = _imgurl + '?x-oss-process=image/resize,m_fill,w_460,h_460';
              canvas.width = 460;
              canvas.height = 460;
              break;
            case 'avatar':
            default:
              //这个设置不能丢，否者会成为canvas默认的300*150的大小
              img.src = _imgurl + '?x-oss-process=image/resize,m_fill,w_128,h_128';
              canvas.width = 128;
              canvas.height = 128;
          }
          var ctx = canvas.getContext('2d');
          img.onload = () => {
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            resolve(canvas.toDataURL());
          };
          img.onerror = (err) => {
            // 图片 url 不存在的时候就让页面继续加载吧。。
            resolve();
          };
        });
      },
    },
  };
</script>
<style lang="less" scoped>
  .share-card {
    // position: relative;
    width: 100%;
    min-height: 100vh;
    background-color: #151826;
    text-align: center;
    position: relative;
    .badge-header {
      height: 100px;
      .page-bottom-open-app {
        top: 0;
      }
    }
    // 分享邀请好友
    .share-signal {
      position: fixed;
      top: 10px;
      right: 20px;
      transition: all 0.2s;
      animation: shake 1.5s infinite;
      p {
        width: 100px;
        height: 30px;
        line-height: 30px;
        background: #111111;
        border-radius: 7px;
        font-size: 14px;
        font-weight: 400;
        color: #ffffff;
        text-align: center;
        margin-left: 180px;
      }
      .triangle {
        width: 0;
        height: 0;
        border-top: 0px solid transparent;
        border-left: 10px solid transparent;
        border-right: 10px solid transparent;
        border-bottom: 10px solid #111111;
        margin-left: 245px;
      }
    }
    .load-box {
      position: absolute;
      top: 25%;
      left: 0;
      right: 0;
      margin: auto;
    }
    // vant 样式修改
    /deep/ .van-nav-bar {
      background-color: transparent;
      .van-nav-bar__left {
        background-image: url(../../assets/images/icon-back-arrow.png);
        background-repeat: no-repeat;
        background-size: 1.8rem;
        background-position: center;
      }
      .van-nav-bar__title {
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #ffffff;
        font-size: 1.7rem;
      }
      .van-nav-bar__arrow {
        font-size: 18px;
      }
      .van-nav-bar__right {
        img {
          width: 2.4rem;
          height: 2.4rem;
        }
      }
      .van-icon {
        color: transparent;
      }
    }
    /deep/ .van-hairline--bottom::after {
      border-bottom-width: 0px;
    }
    .my-nav-bar {
      position: fixed;
      width: 100%;
      top: 0;
      background: #151826;
      height: 8.8rem;
      padding-top: 4.8rem;
    }

    // 这里就是渲染之后展示的页面
    .share-page {
      // position: absolute;
      // top: 70px;
      // bottom: 182px;
      // overflow: scroll;
      margin: 0 20px;
      // width: 335px;
      // height: 1160px;
      // margin: 0 auto;
      // margin-top: 2.3rem;
      overflow: hidden;
      background: #1d2132;
      border-radius: 5px;
      img {
        width: 100%;
        height: 100%;
        -webkit-touch-callout: default !important;
      }
    }
    @media screen and(max-height:568px) {
      .share-page {
        margin-top: 0.5rem;
      }
    }
    // 这里是提供渲染的节点
    .hidden {
      position: fixed;
      left: 30000px;
      top: 30px;
      z-index: 20;
    }
  }
  .scrollBox {
    padding-bottom: 0.2rem;
  }
  @media screen and(max-height:736px) {
    .scrollBox {
      padding-bottom: 12rem;
    }
  }
  @media screen and(max-height:667px) {
    .scrollBox {
      padding-bottom: 16rem;
    }
  }
  .content {
    width: 335px;
    // height: 520px;
    // overflow: scroll;
    // border-radius: 5px 5px 0px 0px;
    content: '';
    position: relative;
    background-color: #1d2132;
    background-size: contain;
  }
  @media screen and (max-height: 750px) {
    .content {
      width: 375px;
    }
  }
  @media screen and (max-height: 680px) {
    .content {
      width: 335px;
    }
  }
  @media screen and (max-height: 570px) {
    .content {
      width: 280px;
    }
  }

  .back {
    height: 100%;
    background: url(../../assets/images/badge/share-badgewall.png) no-repeat;
    background-color: #1d2132;
    background-size: contain;
  }
  .info-header {
    // border-radius: 5px 5px 0px 0px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 28px 18px 0 18px;
    &.onlyone {
      position: absolute;
      z-index: 111;
      left: 0;
      right: 0;
    }
  }
  .info {
    display: flex;
    align-items: center;
  }
  .avatar {
    width: 32px;
    height: 32px;
    border: 2px solid rgba(255, 255, 255, 0.15);
    background-size: cover;
    border-radius: 50%;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .name {
    width: 140px;
    text-align: left;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #ffffff;
    margin-left: 8px;
  }
  .badge-num {
    font-size: 12px;
    font-family: PingFangSC-Light, PingFang SC;
    font-weight: 300;
    color: rgba(255, 255, 255, 0.6);
    .num {
      font-size: 18px;
      font-family: DIN-Bold, DIN;
      font-weight: bold;
      color: #ffffff;
    }
  }
  .info-badge {
    min-height: 390px;
    // overflow-y: scroll;
    // width: 335px;
    margin: 0 auto;
    padding: 30px 15px 50px 15px;
    display: grid;
    grid-template-columns: repeat(2, 50%);
    grid-row-gap: 30px;
  }
  @media screen and (max-height: 736px) {
    .info-badge {
      min-height: 345px;
    }
  }
  @media screen and (max-height: 667px) {
    .info-badge {
      min-height: 285px;
    }
  }
  @media screen and (max-height: 568px) {
    .info-badge {
      min-height: 235px;
    }
  }
  .badge-item {
  }
  .wall-img {
    position: relative;
    margin: 0 auto;
    width: 108px;
    height: 108px;
    background-size: contain;
    img {
      border-radius: 50%;
      width: 100%;
      height: 100%;
      padding: 5px;
    }
  }
  .wall-title {
    text-align: center;
    width: 70px;
    margin: 0 auto;
    margin-top: 13px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(250, 250, 250, 0.9);
    word-wrap: break-word;
  }
  .info-footer {
    display: flex;
    align-items: center;
    padding: 15px 20px 15px 15px;
    justify-content: space-between;
    background-color: #fff;
    // border-radius: 0px 0px 5px 5px;
  }
  .info-title {
    font-size: 14px;
    text-align: left;
    text-indent: -0.5rem;
    line-height: 20px;
    margin-left: 10px;
  }
  .invite {
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #111111;
  }
  .title {
    font-family: PingFangSC-Light, PingFang SC;
    font-weight: 300;
    color: #111111;
  }
  .info-box {
    display: flex;
    align-items: center;
    canvas {
      width: 50px;
      height: 50px;
      // margin-right: 1.5rem;
      flex: none;
    }
  }
  .icon-jimu {
    width: 70px;
    height: 23px;
    background-size: contain;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .info-badge-single {
    position: relative;
    // padding: 30px 15px 50px 15px;
  }
  .outer-box {
    width: 100%;
    // padding-top: 15px;
    // padding-bottom: 65px;
    // height: 305px;
    display: flex;
    align-items: center;
    position: relative;
  }
  .test {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
    .bg {
    }
    .badge-img {
      flex: none;
      width: 143px !important;
      height: 143px !important;
      position: absolute;
      display: block;
    }
  }
  .box-height {
    height: 18.2rem;
  }
  .badge-launch {
    display: flex;
    align-items: center;
    position: absolute;
    left: 0;
    right: 0;
    z-index: 999;
    width: 335px;
    height: 335px;
    // background: url(../../assets/images/badge/icon-launch-opacity.png) no-repeat;
    // background: url(../../assets/images/badge/share-badge-bg.png) no-repeat;
    background-size: cover;
    margin: 0 auto;
  }
  .badge-filter {
    display: flex;
    align-items: center;
    margin: 0 auto;
    width: 229px;
    height: 229px;
    // background: url(../../assets/images/badge/share-filter-opacity.png) no-repeat;
    background-size: contain;
    // opacity: 0.7;
  }
  .badge-start {
    // position: absolute;
    // top: 35%;
    // left: 0;
    // right: 0;
    z-index: 999;
    margin: 0 auto;
    width: 229px;
    height: 90px;
    // background: url(../../assets/images/badge/share-starts.png) no-repeat;
    // background-size: contain;
    img {
      width: 100%;
    }
  }
  .badge-image {
    z-index: 999;
    // position: absolute;
    // top: 25%;
    // left: 0;
    // right: 0;
    margin: 0 auto;
    width: 128px;
    height: 128px;
    background-size: contain;
    border-radius: 50%;
    box-shadow: 0px 14px 16px rgba(0, 0, 0, 0.3);
    img {
      width: 100%;
      height: 100%;
    }
  }
  @media screen and (max-height: 736px) {
    .badge-image {
      width: 118px;
      height: 118px;
    }
  }
  @media screen and(max-height:667px) {
    .badge-image {
      width: 103px;
      height: 103px;
    }
  }
  @media screen and(max-height:568px) {
    .badge-image {
      width: 93px;
      height: 93px;
    }
  }
  .bottom-title {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    // margin-top: 20px;
  }
  .badge-title {
    font-size: 21px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #ffffff;
  }
  .work-num {
    margin-top: 10px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(250, 250, 250, 0.8);
  }
  @media screen {
  }
  .jimu-app {
    // margin-left: -28px;
    margin-top: 20px;
    height: 65px;
    // background: url(../../assets/images/badge/icon-jimu.png) no-repeat;
    background-size: cover;
    opacity: 0.5;
    img {
      width: 100%;
      height: 100%;
    }
  }

  @media screen and (max-height: 750px) {
    .outer-box {
      padding-top: 0px;
      padding-bottom: 35px;
    }
    .badge-launch {
      width: 209px;
      height: 209px;
    }
    .badge-filter {
      width: 209px;
      height: 209px;
    }
    .jimu-app {
      height: 55px;
    }
  }
  @media screen and(max-height:680px) {
    .outer-box {
      margin-top: -10px;
      padding-top: 0px;
      padding-bottom: 15px;
    }
    .badge-launch {
      width: 199px;
      height: 199px;
    }
    .badge-filter {
      width: 199px;
      height: 199px;
    }
    .jimu-app {
      height: 50px;
    }
  }
  @media screen and(max-height:568px) {
    // .outer-box {
    //   height: 180px;
    // }
    .badge-launch {
      width: 179px;
      height: 179px;
    }
    .badge-filter {
      width: 179px;
      height: 179px;
    }
    .jimu-app {
      height: 40px;
    }
    .badge-title {
      font-size: 16px;
    }
    .work-num {
      font-size: 10px;
    }
    .info-footer {
      padding: 10px 15px;
    }
  }
</style>
